package com.apobates.forum.bucket.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.apobates.forum.utils.DateTimeUtils;
import com.apobates.forum.utils.fileupload.UploadInitParamers;
import com.apobates.forum.utils.fileupload.ckeditor.CKEditorHightHandler;

/**
 * CKEditor的上传
 * @author xiaofanku@live.cn
 * @since 20191023
 */
public class UploadEditorFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String uploadImageDirectName; 
	private String siteDomain; 
	private long uploadMaxByte;
	private final static Logger logger = LoggerFactory.getLogger(UploadEditorFileServlet.class);

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		//子目录
		String childDirect = DateTimeUtils.getYMD();
		// 项目路径
		final String realPath = request.getServletContext().getRealPath("/") + File.separator + uploadImageDirectName + File.separator + childDirect;
		// 前台访问路径
		final String frontVisitPath = siteDomain + uploadImageDirectName + "/"+childDirect+"/";
		UploadInitParamers cip = new UploadInitParamers() {
			@Override
			public String getFileSaveDir() {
				return realPath;
			}

			@Override
			public String getCallbackFunctionName() {
				// 没有回调函数
				return null;
			}

			@Override
			public String getUploadFileInputName() {
				return "upload";
			}

			@Override
			public HttpServletRequest getRequest() {
				return request;
			}
		};
		String outResult=null; 

		try {
			ServletFileUploadConnector connector = new ServletFileUploadConnector(new CKEditorHightHandler(frontVisitPath, uploadMaxByte));
			String responsebody = connector.upload(cip);
			outResult = CKEditorHightHandler.buildCkeditorResponse(true, "上传成功", responsebody.replace(frontVisitPath, ""), responsebody);
		} catch (Exception e) {
			String errorMesg = e.getMessage();
			logger.info("[UEFS]异常消息: "+errorMesg);
			if (logger.isDebugEnabled()) {
				logger.debug(errorMesg, e);
			}
			outResult = CKEditorHightHandler.buildCkeditorResponse(false, errorMesg);
		}
		logger.info("[UEFS]输出响应: "+outResult);
		//
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		try(PrintWriter out = response.getWriter()){
			out.write(outResult);
			out.flush();
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		try (PrintWriter out = resp.getWriter()) {
			out.println("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>Access Denied</title></head><body><p>暂不支持浏览功能</p></body></html>");
			out.flush();
		}
	}
	
	/**
	 * 获得初始化值
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.siteDomain = config.getInitParameter("siteDomain"); //站点URL, http://xx.com
		this.uploadImageDirectName = config.getInitParameter("uploadImageDirectName"); //图片保存的目录
		this.uploadMaxByte = 5242880; //5M
		try{
			uploadMaxByte=Long.valueOf(config.getInitParameter("uploadMaxByte")); //multipart-config.max-request-size
		}catch(NullPointerException | NumberFormatException e){}
	}
}
